/**
 * 多重任务
 * 将多个任务放在数组中，然后传给这个类，它会回调各个任务，并且支持开始、暂停等操作。方便对每个任务进行处理
 * @param tasks 任务组成的数组
 * @param period 每两个任务之间的时间间隔（比如在判断域名是否存在的时候，需要设置一个时间间隔，避免被封）
 * @data 2018 01 27
 * @author yueya
 */
function MultiTask(_tasks, _period){
	if(!arguments[0])_tasks = [];
	if(!arguments[1])_period = 0;
	
	var self = this;
	var tasks = _tasks;
	var period = _period;
	
	var Status = {
		STOP : 0,
		RUNNING : 1,
		WAITING : 2,
	};
	
	var currKey = 0;//准备执行的任务ID
	var finId = -1;//已完成的任务中，最新完成一个任务的ID  用途：比如暂停后重新开始，从此ID+1开始执行即可
	var status = Status.STOP;// 状态 enum{stop, running, waiting, pause}
	var order = "";//命令 enum{pause}
	
	
	var constructor = function(){

	}();
	
	
	var execute = function(key){
		
		if(status == Status.RUNNING){
			if(key > tasks.length || key <0){
				alert("任务KEY错误");
				status = Status.STOP;
				return;
			}
			currKey = key;
			if(currKey < (tasks.length)){
				var task = tasks[key];
				
				if(period > 0){
					setTimeout(function(){
						if(status == Status.RUNNING){//如果中途按停止或暂停，此处禁止执行
							self.onTask(currKey, task);
						}
					}, period);
				}else{
					self.onTask(currKey, task);
				}
			}else{
				status = Status.STOP;
				currKey = 0;
				self.onEnd();	
			}
		}else{
			
		}
	}

	/**
	 * abstract 等待回调
	 */
	this.onTask = function(key, task){};
	this.onEnd = function(){};
	this.onInfo = function(info){};
	
	//由外部触发的开始按钮
	this.start = function(key){
		if(status == Status.RUNNING){
			alert("任务运行中，请勿重复开始");
		}else if(status == Status.STOP){
			status = Status.RUNNING;
			if(!key)execute(currKey);
			else execute(key);
		}
	}
	
	this.success = function(){
		currKey++;
	}

	this.retry = function(){
		execute(currKey);
	}
	
	this.next = function(){
		self.success();
		execute(currKey);
	}
	
	this.pause = function(){
		if(status == Status.RUNNING){
			status = Status.STOP;
		}else if(status == Status.STOP){
			alert("任务已经停止，请勿重复操作");
		}
	}
	
	this.stop = function(){
		if(status == Status.RUNNING){
			currKey = 0;
			status = Status.STOP;
		}else if(status == Status.STOP){
			alert("任务已经停止，请勿重复操作");
		}
	}
}